<?php

	require_once "../../konfigurasi.php";
	
	koneksi_buka();
	
	if(isset($_GET['id'])){
		$id = $_GET['id'];
	}
	
	if(isset($_POST['id'])){
		$id = $_POST['id'];
	}
	
	if(isset($_POST['soal_id'])){
		$soal_id = $_POST['soal_id'];
	}
	
	if(isset($_POST['hasil'])){
		$hasil = $_POST['hasil'];
	}
	
	if(isset($_POST['no'])){
		$no = $_POST['no'];
	}
	
	if(isset($_POST['lanjut'])){
		$lanjut = $_POST['lanjut'];
	}
	
	if(isset($_POST['pilihan'])){
		$pilihan = $_POST['pilihan'];
	}
			
	$tgl_daftar = date("Y-m-d");
	$wkt = date("H:i:s");
	
	$q_d_soal = mysql_query("select * from d_soal where no='$no' and soal_id = '$soal_id'");
	
	if($dt_d_soal = mysql_fetch_array($q_d_soal)) {
		
		if($dt_d_soal['jawaban_pilihan_no']==$pilihan){
			$benar = 1;
		}else{
			$benar = 0;
		}
	}
	
	$q_d_hasil_soal = mysql_query("select * from d_hasil_soal where no_d_soal='$no' and hasil='$hasil'");
	
	if($dt_d_hasil_soal = mysql_fetch_array($q_d_hasil_soal)) {
		
		$result = mysql_query("UPDATE d_hasil_soal SET
			jawaban_hasil = '$pilihan',
			benar = '$benar'
			WHERE no_d_soal='$no' and hasil='$hasil'");
			
		if($result){
			if($lanjut!="end"){
				header("Location:../../soal.php?soal_id=$soal_id&no=$lanjut");
			}
			
		}else{
			echo 'failed';
		}

	}else{
		$q = "INSERT INTO d_hasil_soal
			(no_d_soal, jawaban_hasil, hasil, benar) 
			VALUES('$no', '$pilihan', '$hasil', '$benar')";
		$result = mysql_query($q);
		if($result){
			if($lanjut!="end"){
				header("Location:../../soal.php?soal_id=$soal_id&no=$lanjut");
			}else{
				
				$q_count_nilai = "select sum(benar) as benar, count(benar) as total from d_hasil_soal where hasil = $hasil group by hasil";
				if($dt = mysql_fetch_array(mysql_query($q_count_nilai))){
					$benar = $dt['benar'];
					$total = $dt['total'];
					$nilai = (100/$total)*$benar;
					$q_update_hasil_nilai = "update hasil_soal set nilai = $nilai where id = $hasil";
					$result = mysql_query($q_update_hasil_nilai);
					if($result){
						header("Location:../../hasil_latihan.php?soal_id=$soal_id");	
					}
					
				}
				
			}
		}else{
			echo 'failed query :'.$q ;
		}
	}
		
	
	
	
?>
